import { defineStore } from "pinia";
import { ref } from "vue";
import type { RouteLocationNormalizedLoaded } from "vue-router";
/**
 * @description: 标签页
 * @param {*} defineStore
 * @return {*}
 */
export const useTabsStore: any = defineStore("tabs", () => {
  const tabs = ref<RouteLocationNormalizedLoaded[]>([]);
  tabs.value = [] as unknown as RouteLocationNormalizedLoaded[];
  const testTaskId = ref("");

  /**
   * @description: 添加标签
   * @param {RouteLocationNormalizedLoaded} route
   * @return {*}
   */
  const addTab = (route: RouteLocationNormalizedLoaded) => {
    if (route.meta.hideTabs) return;
    const k = route.meta.tabType === "multiple" ? "fullPath" : "path";
    const isExists = tabs.value.find((tab) => tab.meta.affix || tab[k] === route[k]);
    if (!isExists) {
      tabs.value.push(route);
    }
  };
  /**
   * @description: 清空标签
   * @return {*}
   */
  const clear = () => {
    tabs.value = tabs.value.filter((tab) => tab.meta.affix);
  };
  /**
   * @description: 更改标签标题
   * @param {RouteLocationNormalizedLoaded} route
   * @param {string} value
   * @return {*}
   */
  const setTab = (route: RouteLocationNormalizedLoaded, value: string) => {
    const k = route.meta.tabType === "multiple" ? "fullPath" : "path";
    const item = tabs.value.find((tab) => tab[k] === route[k]);
    item && (item.meta.name = value);
  };

  /**
   * @description: 关闭标签
   * @param {RouteLocationNormalizedLoaded} route
   * @return {*}
   */
  const closeTab = (route: RouteLocationNormalizedLoaded, key: "self" | "other" | "right" | "all") => {
    const k = route.meta.tabType === "multiple" ? "fullPath" : "path";
    key === "self" && (tabs.value = tabs.value.filter((tab) => tab.meta.affix || tab[k] !== route[k]));
    key === "other" && (tabs.value = tabs.value.filter((tab) => tab.meta.affix || tab[k] === route[k]));
    if (key === "right") {
      const index = tabs.value.findIndex((tab) => tab[k] === route[k]);
      tabs.value = tabs.value.filter((tab, i) => tab.meta.affix || i <= index);
    }
    key === "all" && clear();
  };
  return { tabs, addTab, closeTab, clear, setTab, testTaskId };
});
